package com.xique.blelock.Utils;

import android.bluetooth.BluetoothGatt;
import android.content.Context;
import android.os.Handler;
import android.os.ParcelUuid;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.utils.HexUtil;
import com.ivin.crop.Log;
import com.xique.blelock.Interface.BleConnectListen;
import com.xique.blelock.Interface.BleListenData;
import com.xique.blelock.Interface.BleNotificationListen;
import com.xique.blelock.view.BaseActivity;
import com.xique.blelock.view.DeviceManager.DeviceControllerActivity;

import java.util.UUID;

/**
 * Created by Administrator on 2018/12/12.
 */

public class BleUtils {

    private static BleDevice mbleDevice;

    private static BleListenData mbleListen;

    private static BleConnectListen connectListen;

    private static BleNotificationListen bleNotificationListen;

    private static BaseActivity mContext;


    public static BleDevice getBleDevice() {
        return mbleDevice;
    }

    public static  void setBleDevice(BleDevice bleDevice) {
        mbleDevice = bleDevice;
    }

    public BleListenData getBleListen() {
        return mbleListen;
    }

    public static  void setBleListen(BleListenData bleListen) {
        mbleListen = bleListen;
    }

    public static BleConnectListen getConnectListen() {
        return connectListen;
    }

    public static void setConnectListen(BleConnectListen connectListen) {
        BleUtils.connectListen = connectListen;
    }

    public static BleNotificationListen getBleNotificationListen() {
        return bleNotificationListen;
    }

    public static void setBleNotificationListen(BleNotificationListen bleNotificationListen) {
        BleUtils.bleNotificationListen = bleNotificationListen;
    }

    private static int notifytime = 0;
    public static void setNofifyCation(){
        notifytime = 0;
        BleManager.getInstance().notify(mbleDevice,Stringkey.SERVICE_UUID,Stringkey.NOTIFY_CHAR_UUID,bleNotifyCallback);


    }

    //接受数据监听
    private static BleNotifyCallback bleNotifyCallback = new BleNotifyCallback() {
        @Override
        public void onNotifySuccess() {
            // 打开通知操作成功
            Log.e("打开通知成功：", "");
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    BleManager.getInstance().notify(mbleDevice,Stringkey.SERVICE_UUID, Stringkey.RECORD_NOTIFY_CHAR_UUID,bleNotifyCallback2);

                }
            }, 200);
        }

        @Override
        public void onNotifyFailure(BleException exception) {
            // 打开通知操作失败
            Log.e("打开通知失败：", "");
            //再来一次
            if(bleNotificationListen != null){
                bleNotificationListen.didNotification(null, false);
            }
        }

        @Override
        public void onCharacteristicChanged(byte[] data) {
            // 打开通知操作成功
            String rep = HexUtil.encodeHexStr(data);
            Log.e("接受到数据："+ rep, "");
            if(mbleListen != null){
                mbleListen.didReciveData(data);
            }
        }
    };
    private static BleNotifyCallback bleNotifyCallback2 = new BleNotifyCallback() {
        @Override
        public void onNotifySuccess() {
            // 打开通知操作成功
            Log.e("打开通知成功2：", "");
            if(bleNotificationListen != null){

                bleNotificationListen.didNotification(null, true);
            }

        }

        @Override
        public void onNotifyFailure(BleException exception) {
            // 打开通知操作失败
            Log.e("打开通知失败2：", "");
            if(bleNotificationListen != null){
                bleNotificationListen.didNotification(null, false);
            }
        }

        @Override
        public void onCharacteristicChanged(byte[] data) {
            // 打开通知操作成功
            String rep = HexUtil.encodeHexStr(data);
            Log.e("接受到数据2："+ rep, "");
            if(mbleListen != null){
                mbleListen.didReciveData(data);
            }

        }
    };

    public static void sendData(byte[] data){
        BleManager.getInstance().write(mbleDevice,Stringkey.SERVICE_UUID, Stringkey.WRITE_CHAR_UUID, data,bleWriteCallback);
    }

    public static void sendData(String datstr){
        sendData(HexUtil.hexStringToBytes(datstr));
    }

    private static BleWriteCallback bleWriteCallback = new BleWriteCallback() {
        @Override
        public void onWriteSuccess(int current, int total, byte[] justWrite) {
            Log.e("数据发送完成：" + HexUtil.encodeHexStr(justWrite), "");

        }

        @Override
        public void onWriteFailure(BleException exception) {
            Log.e("数据发送失败"+ exception.getDescription(), "");

        }
    };


    public static void stopNotify() {
        BleManager.getInstance().stopNotify(mbleDevice,Stringkey.SERVICE_UUID,Stringkey.NOTIFY_CHAR_UUID);
        BleManager.getInstance().stopNotify(mbleDevice,Stringkey.SERVICE_UUID,Stringkey.RECORD_NOTIFY_CHAR_UUID);
    }

    public static void connectDev(BleDevice bleDevice , Context context){
        mContext = (BaseActivity) context;
//        mContext.showProgressDialog();
        BleManager.getInstance().connect(bleDevice, bleGattCallback);
    }

    public static void connectDev(String blemac, Context context){
        mContext = (BaseActivity) context;
//        mContext.showProgressDialog();
        BleManager.getInstance().connect(blemac, bleGattCallback);
    }

    //蓝牙连接回调接口
    private static  BleGattCallback bleGattCallback = new BleGattCallback() {
        @Override
        public void onStartConnect() {
            // 开始连接
            Log.e("开始连接------------：", "");
        }

        @Override
        public void onConnectFail(BleDevice bleDevice, BleException exception) {
            // 连接失败
//            hideProgressDialog();
//            mContext.showToast(mContext, "连接失败");
            Log.e("连接失败-------------："+bleDevice.getName(), "");
//            mContext.hideProgressDialog();
            if(connectListen != null){
                connectListen.didDisConnect(bleDevice);
            }
        }

        @Override
        public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
            // 连接成功，BleDevice即为所连接的BLE设备
            //连接成功，需要跳转到下一个控制界面
            Log.e("已经连接上设备-----------："+bleDevice.getName(), "");
            if(connectListen != null){
                connectListen.didConnetced(bleDevice);
            }
//            mContext.hideProgressDialog();
        }

        @Override
        public void onDisConnected(boolean isActiveDisConnected, BleDevice bleDevice, BluetoothGatt gatt, int status) {
            // 连接中断，isActiveDisConnected 表示是否是主动调用了断开连接方法
            if(connectListen != null){
                connectListen.didDisConnect(bleDevice);
            }
            mContext.showToast(mContext,"设备断开了");
            Log.e("设备断开----------："+bleDevice.getName(), "");
        }
    };

    public static boolean cotainUUID(BleDevice bleDevice, String serviceUuid) {
        ParcelUuid[] uuids = bleDevice.getDevice().getUuids();
        if(uuids == null || uuids.length == 0){
            return false;
        }
        for(ParcelUuid parceuuid: uuids){
            UUID uuidtemp = parceuuid.getUuid();
            if(uuidtemp.toString().equalsIgnoreCase(serviceUuid)){
                return true;
            }
        }

        return false;

    }

    public static void disConnectDevice() {
        BleManager.getInstance().disconnect(mbleDevice);
    }
}
